exports.install = function(Vue, options) {
	//httpRequest  网络请求
	/**
	 * @param {Object} reqObj url(路径) data(参数) method(有效值)
	 * @param {Object} callbackSuccess callbackSuccess 成功回调函数
	 * @param {Object} callbackFail callbackFail 失败回调函数
	 */
	Vue.prototype.req = function(reqObj, callbackSuccess, callbackFail) {

		let domain = this.GLOBAL.domain;
		let reqHeader = uni.getStorageSync('user_info') ? uni.getStorageSync('user_info').header : '';
		let urlId = reqObj.id ? '/' + reqObj.id : "";
		console.log(JSON.stringify(reqObj.data));
		uni.request({

			url: domain + reqObj.url + urlId, //接口路径
			data: reqObj.data, //接口参数 
			dataType: 'json',
			method: reqObj.method || 'post',

			header: {
				'authorization': reqHeader //自定义请求头信息
			},

			success: (res) => {

				callbackSuccess(res);

			},

			fail: (res) => {
				uni.showToast({
					title: '请稍后重试'
				});
				if (callbackFail) callbackFail(res);
			}
		});

	};

	//手机应用程序启动配置

	Vue.prototype.isApp = function() {

		// 锁定屏幕方向
		plus.screen.lockOrientation("portrait-primary"); //锁定
		// console.log(plus.runtime.version);
		this.req({
			url: 'both/getAppSetting',
			method: 'get',
			data: {
				appid: plus.runtime.appid,
				version: plus.runtime.version,
				imei: plus.device.imei
			}
		}, (res) => {
			console.log(res);
			console.log('请求成功');
			if (res.data.status == 1) {

				uni.setStorageSync("system_config", res.data.data.system_config);
				uni.setStorageSync('new_version', res.data.data.app_version_info);

			}
		}, (res) => {
			console.log(res);
		});
		// // 检测升级
		// uni.request({
		// 	url: "https://uniapp.dcloud.io/update", //检查更新的服务器地址
		// 	data: {
		// 		appid: plus.runtime.appid,
		// 		version: plus.runtime.version,
		// 		imei: plus.device.imei
		// 	},
		// 	success: res => {
		// 		console.log("success", res);
		// 		if (res.statusCode == 200 && res.data.isUpdate) {
		// 			let openUrl =
		// 				plus.os.name === "iOS" ? res.data.iOS : res.data.Android;
		// 			// 提醒用户更新
		// 			uni.showModal({
		// 				title: "更新提示",
		// 				content: res.data.note ? res.data.note : "是否选择更新",
		// 				success: showResult => {
		// 					if (showResult.confirm) {
		// 						plus.runtime.openURL(openUrl);
		// 					}
		// 				}
		// 			});
		// 		}
		// 	}
		// });


	};
	Vue.prototype.isWx = function() {
		this.req({
			url: 'both/getAppSetting',
			method: 'get'
		}, (res) => {
			console.log(res);
			if (res.data.status == 1) {
				uni.setStorageSync("system_config", res.data.data.system_config);
			}
		}, (res) => {

		});
	}
	//用户登录完成
	Vue.prototype.afterLogin = function(userData) {

		/**
		 * 存储用户信息到APP 
		 */

		const info = userData;

		uni.setStorageSync('user_info', {
			head_images: info.head_images, //用户ID 
			balance: info.balance, //用户姓名
			create_time: info.create_time, //用户电话
			id: info.id,
			open_id: info.open_id,
			phone: info.phone,
			type: info.type,
			header: info.user_Token,
			username: info.username,
			uuid: info.id,
			hotel_id: info.hotel_id,
			say: info.say,
			adress: info.adress
		});
		uni.setStorageSync('terminalType', info.type);
		
		this.$store.commit('login', info);
		this.$store.commit('changeType', info.type);
		this.userInfoCache();
		/**
		 * 推送用户ID
		 */
		uni.sendSocketMessage({
			data:this.isLogin()?this.isLogin().id:''
		});

	};
	//判断是否登录 已登录获取用户信息
	Vue.prototype.isLogin = function() {
		const loginSta = uni.getStorageSync('user_info');

		if (loginSta) {
			// return loginSta.loginSta.openID;
			return uni.getStorageSync('user_info');
		} else {
			return false;
		}


	};

	Vue.prototype.updateUserInfo = function() {
		/**
		 * 更新用户信息
		 */
		const userInfo = uni.getStorageSync('user_info');
		const terminalType = uni.getStorageSync('terminalType')
		if (userInfo) this.$store.commit('login', userInfo);
		if (terminalType) this.$store.commit('changeType', terminalType);
	};
	Vue.prototype.logout = function() {
		/**
		 * 用户退出登录
		 */
		uni.removeStorage({
			key: 'user_info'
		});
		uni.removeStorage({
			key: 'terminalType'
		});
		uni.removeStorage({
			key: 'hotel_info'
		});
		uni.removeStorage({
			key: 'user'
		});

		uni.removeStorage({
			key: 'user_wx_info'
		});
		this.$store.commit('logout');
		uni.reLaunch({
			url: '/pages/index/index'
		});
	};
	Vue.prototype.termTypeUpdate = function(terminalType) {
		/**
		 * 更新用户端口类型
		 */
		uni.setStorageSync('terminalType', terminalType);
		this.modifyUserInfo('type', terminalType);
		this.$store.commit('changeType', terminalType);
	};
	Vue.prototype.modifyUserInfo = function(key, value) {
		/**
		 * 修改本地存储个人信息
		 */
		let userInfo = uni.getStorageSync('user_info');
		let newUserInfo = userInfo;
		newUserInfo[key] = value;

		uni.setStorageSync('user_info', newUserInfo);
	};
	/**
	 * 取消小数点
	 */
	Vue.prototype.regularVerification = function(type, val) {
		/**
		 * 电话验证
		 */
		if (type == 'phone') {
			return (/^1[345789]\d{9}$/.test(val));
		}
		/**
		 * 姓名验证
		 */
		if (type == 'name') {
			return (/^[\u4e00-\u9fa5]{2,6}$/.test(val));
		}
		/**
		 * 座机号码
		 */
		if (type == 'telephone') {
			return (/0\d{2,3}-\d{7,8}/.test(val));
		}
		/**
		 * 金额
		 */
		if (type == 'jine') {
			return (/^\d+(\.\d{1,2})?$/.test(val));
		}
		/**
		 * 身份证
		 */
		if (type == 'id_card') {
			return (/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(val));
		}
	};
	/**
	 * 配置项
	 */
	Vue.prototype.appConfig = function() {
			return uni.getStorageSync('system_config');
		},
		/**
		 * 地图导航
		 */
		Vue.prototype.mapNavigation = function(latitude, longitude, name) {
			// #ifdef APP-PLUS
			var url = "";
			if (plus.os.name == "Android") {
				var hasBaiduMap = plus.runtime.isApplicationExist({
					pname: 'com.baidu.BaiduMap',
					action: 'baidumap://'
				});
				var hasAmap = plus.runtime.isApplicationExist({
					pname: 'com.autonavi.minimap',
					action: 'androidamap://'
				});
				var urlBaiduMap = "baidumap://map/marker?location=" + latitude + "," + longitude + "&title=" + name + "&src=客栈帮手";
				var urlAmap = "androidamap://viewMap?sourceApplication=客栈帮手&poiname=" + name + "&lat=" + latitude + "8&lon=" +
					longitude + "&dev=0"
				if (hasAmap && hasBaiduMap) {
					plus.nativeUI.actionSheet({
						title: "选择地图应用",
						cancel: "取消",
						buttons: [{
							title: "百度地图"
						}, {
							title: "高德地图"
						}]
					}, function(e) {
						switch (e.index) {
							case 1:
								plus.runtime.openURL(urlBaiduMap);
								break;
							case 2:
								plus.runtime.openURL(urlAmap);
								break;
						}
					})
				} else if (hasAmap) {
					plus.runtime.openURL(urlAmap);
				} else if (hasBaiduMap) {
					plus.runtime.openURL(urlBaiduMap);
				} else {
					url = "geo:" + latitude + "," + longitude + "?q=" + name;
					plus.runtime.openURL(url); //如果是国外应用，应该优先使用这个，会启动google地图。这个接口不能统一坐标系，进入百度地图时会有偏差  
				}
			} else {
				// iOS上获取本机是否安装了百度高德地图，需要在manifest里配置，在manifest.json文件app-plus->distribute->apple->urlschemewhitelist节点下添加（如urlschemewhitelist:["iosamap","baidumap"]）  
				plus.nativeUI.actionSheet({
					title: "选择地图应用",
					cancel: "取消",
					buttons: [{
						title: "Apple地图"
					}, {
						title: "百度地图"
					}, {
						title: "高德地图"
					}]
				}, (e) => {
					console.log("e.index: " + e.index + latitude + longitude);
					switch (e.index) {
						case 1:
							url = "http://maps.apple.com/?q=" + name + "&ll=" + latitude + "," + longitude + "&spn=0.008766,0.019441";
							break;
						case 2:
							// url = "baidumap://map/marker?location="+this.latitude+","+this.longitude+"&title=DCloud&src=123";  
							// url = "baidumap://map/geocoder?location="+this.latitude+","+this.longitude+"&src=andr.baidu.openAPIdemo"; 使用地址查找坐标解析
							url = "baidumap://map/marker?location=" + latitude + "," + longitude + "&title=" + name + "&content=" + name +
								"&traffic=on&src=andr.baidu.openAPIdemo"; //title中传汉字会报错
							break;
						case 3:
							url = "iosamap://viewMap?sourceApplication=客栈帮手&poiname=" + name + "&lat=" + latitude + "&lon=" + longitude +
								"&dev=0";
							break;
						default:
							break;
					}
					url = encodeURI(url); //ios 中文title 会报错
					if (url != "") {
						plus.runtime.openURL(url, function(e) {
							plus.nativeUI.alert("本机未安装指定的地图应用");
						});
					}
				})
			}
			// #endif
			// #ifndef APP-PLUS
			uni.showToast({
				icon: 'none',
				title: '小程序暂不支持该功能'
			})
			// #endif
		}

	/**
	 * 异步传参
	 */
	Vue.prototype.getReq = function(reqObj) {
		let domain = this.GLOBAL.domain;
		let reqHeader = uni.getStorageSync('user_info') ? uni.getStorageSync('user_info').header : '';
		let urlId = reqObj.id ? '/' + reqObj.id : "";
		return uni.request({
			url: domain + reqObj.url + urlId, //接口路径
			data: reqObj.data, //接口参数 
			dataType: 'json',
			method: reqObj.method || 'get',
			header: {
				'authorization': reqHeader
			} //自定义请求头信息
		});
	};


	/**
	 * 弹窗封装
	 */
	Vue.prototype.showToast = function(title) {
		uni.showToast({
			title: title,
			icon: 'none'
		})
	}

	/**
	 * 上传七牛云
	 */

	Vue.prototype.qiniuUpload = function(filePath, key) {
			const qiniuUploader = require("./js/qiniuUploader");
			return new Promise((resolve, reject) => {
				uni.request({
					url: this.GLOBAL.token,
					method: 'GET',
					data: {
						id: this.isLogin().id
					},
					success: res => {
						let options = {
							region: 'NCN',
							domain: res.data.data.domain, //七牛云url域名
							key: key, //文件上传七牛云key名称
							uptoken: res.data.data.token, //七牛云后台token
							uptokenFunc: function() {
								return '[yourTokenString]';
							}
						}
						let success = (res) => {
							resolve(res)
						}
						let fail = (err) => {
							reject(err)
						}
						let progress = (res) => {}
						let cancelTask = () => {}
						let before = () => {}
						let complete = () => {}
						qiniuUploader.upload(filePath, success, fail, options, progress, cancelTask, before, complete)
					}
				});
			})
		},

		/**
		 * 密码加密
		 */
		Vue.prototype.aesEncrypt = function(plainText) {
			let CryptoJS = require("crypto-js");
			const AES_KEY = "qq3217834abcdefg"; //16位
			const AES_IV = "1234567890123456"; //16位
			var encrypted = CryptoJS.AES.encrypt(plainText, CryptoJS.enc.Utf8.parse(AES_KEY), {
				iv: CryptoJS.enc.Utf8.parse(AES_IV)
			});
			return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);

		},
		/**
		 * 用户信息缓存
		 */
		Vue.prototype.userInfoCache = function() {
			this.req({
				url: 'user/accountInfo',
				data: {
					id: this.isLogin().id
				},
				method: 'get'
			}, (res) => {
				if (res.data.status == 1) {
					uni.setStorageSync("hotel_info", res.data.data.hotel_info);
					uni.setStorageSync("user", res.data.data.user);
					uni.setStorageSync("user_wx_info", res.data.data.user_wx_info);
				}
			});
		},
		/**
		 * 订单提示音
		 */
		Vue.prototype.orderTips = function() {
			var innerAudioContext = uni.createInnerAudioContext();
			innerAudioContext.autoplay = true;
			innerAudioContext.src = 'http://static.sxkzbs.com/new_orders.mp3';
			innerAudioContext.play();
		},
		/**
		 * 说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。 
		 * 调用：accAdd(arg1,arg2)   
		 * 返回值：arg1加上arg2的精确结果   
		 */
		Vue.prototype.accAdd = function(arg1, arg2) {
			let r1, r2, m;
			try {
				r1 = arg1.toString().split(".")[1].length
			} catch (e) {
				r1 = 0
			}
			try {
				r2 = arg2.toString().split(".")[1].length
			} catch (e) {
				r2 = 0
			}
			m = Math.pow(10, Math.max(r1, r2))
			return (arg1 * m + arg2 * m) / m
		},
		/**
		 * javascript的减法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
		 * 调用：accSub(arg1,arg2) 
		 * 返回值：arg1减上arg2的精确结果  
		 */
		Vue.prototype.accSub = function(arg1, arg2) {
			return this.accAdd(arg1, -arg2);
		},
		/**
		 * javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
		 * 调用：accMul(arg1,arg2)   
		 * 返回值：arg1乘以arg2的精确结果 
		 */
		Vue.prototype.accMul = function(arg1, arg2) {
			let m = 0,
				s1 = arg1.toString(),
				s2 = arg2.toString();
			try {
				m += s1.split(".")[1].length
			} catch (e) {}
			try {
				m += s2.split(".")[1].length
			} catch (e) {}
			return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
		},
		/**
		 * javascript的除法结果会有误差，在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果
		 * 调用：accDiv(arg1,arg2)   
		 * 返回值：arg1除以arg2的精确结果   
		 */
		Vue.prototype.accDiv = function(arg1, arg2) {
			// let t1 = 0,
			// 	t2 = 0,
			// 	r1, r2;
			// try {
			// 	t1 = arg1.toString().split(".")[1].length
			// } catch (e) {};
			// try {
			// 	t2 = arg2.toString().split(".")[1].length
			// } catch (e) {};
			// with(Math) {
			// 	r1 = Number(arg1.toString().replace(".", ""))
			// 	r2 = Number(arg2.toString().replace(".", ""))
			// 	return (r1 / r2) * pow(10, t2 - t1);
			// }
		},
		/**
		 * 计算坐标距离
		 * getFlatternDistance
		 */
		Vue.prototype.getFlatternDistance = function(lat1, lng1, lat2, lng2) {
			const EARTH_RADIUS = 6378137.0; //单位M
			const PI = Math.PI;
			let f = ((lat1 + lat2) / 2) * PI/180.0;
			let g = ((lat1 - lat2) / 2) * PI/180.0;
			let l = ((lng1 - lng2) / 2) * PI/180.0;

			let sg = Math.sin(g);
			let sl = Math.sin(l);
			let sf = Math.sin(f);

			let s, c, w, r, d, h1, h2;
			let a = EARTH_RADIUS;
			let fl = 1 / 298.257;

			sg = sg * sg;
			sl = sl * sl;
			sf = sf * sf;

			s = sg * (1 - sl) + (1 - sf) * sl;
			c = (1 - sg) * (1 - sl) + sf * sl;

			w = Math.atan(Math.sqrt(s / c));
			r = Math.sqrt(s * c) / w;
			d = 2 * w * a;
			h1 = (3 * r - 1) / 2 / c;
			h2 = (3 * r + 1) / 2 / s;

			return d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
		}
		
};
